package com.example.demo.config;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class TokenCheckInterceptor implements HandlerInterceptor {
	
	private RestTemplate restTemplate = new RestTemplate();
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean tokenValidate = false;
		String requestURI = request.getRequestURI();
		String token = request.getHeader("X-Token");
		if(StringUtils.isEmpty(token)) {
			request.setAttribute("errorMsg", "无token");
		}else {
			Map<String, Object> tokenCheckResult = restTemplate.getForObject("http://localhost:8083/oauthDemo/myacceccToken/checkToken?token="+token, Map.class);
			if(20000 == (int)tokenCheckResult.get("code")) {
				Object user = tokenCheckResult.get("message");
				request.getSession().setAttribute("user", user);
				tokenValidate = true;
			}else{
				request.setAttribute("errorMsg", tokenCheckResult.get("message"));
				
			}
		}

		if(tokenValidate == false) {
			System.out.println("正在请求："+requestURI+"，interceptor获取到的X-Token是："+token+"，"+request.getSession().getAttribute("errorMsg"));
			request.getRequestDispatcher("/tokenFailer/tokenError").forward(request, response);
			return false;
		}
		return true;
	}
}
